package com.lntea.factory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.lntea.beans.BeanDefinition;
import com.lntea.beans.BeanReference;
import com.lntea.beans.PropertyValue;

public class AutowireCapableBeanFactory extends AbstractBeanFactory{
	@Override
	protected void applyPropertyValues(Object bean, BeanDefinition beanDefinition) throws Exception {
		for(PropertyValue propertyValue : beanDefinition.getPropertyValues().getPropertyValues()){
			String name = propertyValue.getName();
			Object value = propertyValue.getValue();
			if(value instanceof BeanReference){
				BeanReference reference = (BeanReference) value;
				value = getBean(reference.getRef());
			}
			try {
				Method method = bean.getClass().getDeclaredMethod("set"+name.substring(0, 1).toUpperCase()+
						name.substring(1), value.getClass());
				method.setAccessible(true);
				method.invoke(bean, value);
			} catch(NoSuchMethodException e){
				Field field = bean.getClass().getDeclaredField(name);
				field.setAccessible(true);
				field.set(bean, value);
			}
		}
	}
}
